//获取应用实例
var app = getApp()
const _request = require("../../../utils/request.js"); // 引入require;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseurl: app.globalData.baseurl,
    fileList: []
  },
  //上传前
  beforeRead(e) {
    console.log(e);
  },

  // 上传图片
  afterRead(event) {
    let _this = this
    const {
      file
    } = event.detail;
    wx.uploadFile({
      url: this.data.baseurl + '/store-api/file/batchUpload',
      filePath: file.url,
      name: 'files',
      header: {
        'token': wx.getStorageSync('token') || null
      },
      formData: {
        user: 'test'
      },
      success(res) {
        const data = JSON.parse(res.data).data[0]
        _this.setData({
          fileList: [..._this.data.fileList, {
            ...file,
            url: data,
            deletable: 'true'
          }]
        })
      },
      fail(error) {
        console.log(error);
      },
      complete(res) {
        console.log(res);
      },
    })
  },


  // 删除图片
  ondelete(e) {
    const {
      file
    } = e.detail
    let list = this.data.fileList.filter((item) => {
      return item.url != file.url
    })
    this.setData({
      fileList: list
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取用户个人信息
    _request.get('/storeCenterInfo/getStoreCenterInfo', {
      id: wx.getStorageSync('userid')
    }).then((res) => {
      let fileList = [];
      let list = res.data.data.environmentImg || []
      list.forEach(e => {
        fileList.push({ type: "image",url:e, deletable: 'true'});
      })
      this.setData({
        fileList: fileList,
      });
    }).catch((error) => {
      console.log(error, 'error');
    })
  },
  onAdd: function () {
    let imgs = this.data.fileList.map(item => {
      return item.url
    })
    _request.postObj('/storeCenterInfo/updateEnvironmentImg', {
      storeId: wx.getStorageSync('storeId'),
      imgs: imgs,
    }).then((res) => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack({
          delta: 0
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000,
        })
      }

    }).catch((error) => {
      console.log(error, 'error');
    })
  }


})